import { useState, useEffect } from "react";
import Image from "next/image";
import styles from "./myCarousel.module.scss";

interface BannerProps {
  src: string;
  alt: string;
  className?: string;
  width?: number;
  height?: number;
}

const MyCarousel = ({ bannerData }: { bannerData: BannerProps[] }) => {
  const switchTime = 5000;
  const [currentPic, setCurrentPic] = useState(0);

  useEffect(() => {
    if (bannerData.length <= 1) return;

    const interval = setInterval(() => {
      setCurrentPic((prevIndex) => {
        const nextIndex = (prevIndex + 1) % bannerData.length; // 取余数，如果prevIndex为bannerData.length - 1，则nextIndex为0
        return nextIndex;
      });
    }, switchTime);

    return () => clearInterval(interval);
  }, [bannerData.length]);

  return (
    <div>
      {bannerData.length > 0 && (
        <div className={styles.bannerPicture}>
          <Image
            src={bannerData[currentPic].src}
            alt={bannerData[currentPic].alt}
            className={bannerData[currentPic].className}
            width={bannerData[currentPic].width || 100}
            height={bannerData[currentPic].height || 100}
            priority
          />
        </div>
      )}
    </div>
  );
};
export default MyCarousel;
